﻿using Entity.System.DTO.Login;
using FrameWork.DataContext;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.System
{
    public class LoginService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * Token生成器
         */
        private readonly TokenService _tokenService;

        /**
         * 构造注入
         */
        public LoginService(DataContext context, TokenService tokenService)
        {
            _context = context;
            _tokenService = tokenService;
        }

        /**
         * 登录
         */
        public async Task<RequestResponseModel<string>> Login(LoginDTO loginDTO)
        {
            //查找账号
            var query = await _context.StaffView.FirstOrDefaultAsync(a => a.Account == loginDTO.Account);

            //找不到账号
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "找不到该用户!", loginDTO.Account);
            }

            //账号或者密码错误
            if (query.Password != loginDTO.Password)
            {
                return RequestResponse.CreateResponse(400, "账号或者密码错误!", loginDTO.Account);
            }

            //生成token
            var token = _tokenService.GenerateToken(query.Id);

            //返回Token
            return RequestResponse.CreateResponse(200, "登录成功", token);
        }
    }
}
